package com.common.utils.poi;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;

public class MyDataHandler  implements ExcelHandlerAdapter{

    @Override
    public Object format(Object value, String[] args, Cell cell, Workbook wb)
    {
        // value 为返回单元格显示内容值
        // args 为excel注解传递的args数组值
        // cell 为单元格对象
        // wb 为工作簿对象
        if (args !=null && args.length >0){
            String type = args[0];
            if (type.equals("金额")){
                BigDecimal fee = getBigDecimal(value);
                BigDecimal divisor = new BigDecimal("10000");
                value = fee.equals(BigDecimal.ZERO)?BigDecimal.ZERO:fee.divide(divisor,6, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
            }else if(type.equals("金额-元")){
                BigDecimal fee = getBigDecimal(value);
                value = fee.stripTrailingZeros().toPlainString();
            }
        }
        return value;
    }

    public static BigDecimal getBigDecimal(Object value) {
        BigDecimal ret = null;
        if (value != null) {
            if (value instanceof BigDecimal) {
                ret = (BigDecimal) value;
            } else if (value instanceof String) {
                ret = new BigDecimal((String) value);
            } else if (value instanceof BigInteger) {
                ret = new BigDecimal((BigInteger) value);
            } else if (value instanceof Number) {
                ret = new BigDecimal(((Number) value).doubleValue());
            } else {
                throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
            }
        }
        return ret;
    }
}
